<template>
  <view class="page">
    <view class="content" id="publicsentiment">
      <view class="main">
        <uv-form labelPosition="left" :model="formData" ref="form">
          <uv-form-item :label="$t('组织')" @click="popup1open">
            <view class="view_input">
              <view class="view_input_left">
                <text>{{ poiId }}</text>
              </view>
              <view class="view_input_right">
                <uv-icon name="arrow-right" size="12"></uv-icon>
              </view>
            </view>
          </uv-form-item>
        </uv-form>
        <view class="main-pingfen">
          <view class="main-pingfen-top"> </view>
          <view class="main-pingfen-date">
            <view
              @click="dateacitve = 'd'"
              :class="dateacitve === 'd' ? 'active' : ''"
              >{{ $t("1日") }}</view
            >
            <view
              @click="dateacitve = 'w'"
              class="border"
              :class="dateacitve === 'w' ? 'active' : ''"
              >{{ $t("7日") }}
            </view>
            <view
              @click="dateacitve = 'm'"
              :class="dateacitve === 'm' ? 'active' : ''"
              >{{ $t("30日") }}</view
            >
            <view
              @click="dateacitve = 'month'"
              :class="dateacitve === 'month' ? 'active' : ''"
              >{{ $t("本月") }}</view
            >
          </view>
        </view>
        <Yellow
          v-if="red_selectedshow0"
          :list="list"
          :id="red_selected"
          :show="show"
          :type="0"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="服务-正面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="red_selectedshow1"
          :list="list"
          :id="red_selected"
          :show="show"
          :type="1"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="服务-负面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="blue_selectedshow0"
          :list="list"
          :id="blue_selected"
          :show="show"
          :type="0"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="环境-正面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="blue_selectedshow1"
          :list="list"
          :id="blue_selected"
          :show="show"
          :type="1"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="环境-负面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="green_selectedshow1"
          :list="list"
          :id="green_selected"
          :show="show"
          :type="1"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="安全-负面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="yellow_selectedshow0"
          :list="list"
          :id="yellow_selected"
          :show="show"
          :type="0"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="性价比-正面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="yellow_selectedshow1"
          :list="list"
          :id="yellow_selected"
          :show="show"
          :type="1"
          :identifycommentlabelcount="identifycommentlabelcount"
          name="性价比-负面评价"
          @click1="click"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
        <Yellow
          v-if="product_selectedshow1"
          :list="list"
          :id="product_selected"
          :show="show"
          :type="true"
          :identifycommentlabelcount="productcount"
          name="产品"
          @click1="click1"
        >
          <template #default="defaultProps">
            <ec-canvas
              v-if="defaultProps.show"
              :id="defaultProps.id"
              :canvas-id="defaultProps.canvasId"
              :ec="defaultProps.ec"
            ></ec-canvas>
          </template>
        </Yellow>
      </view>
    </view>
  </view>
  <uv-popup
    ref="popup1"
    mode="bottom"
    @change="(e: any) => pageshow = e.show"
    :safeAreaInsetBottom="false"
  >
    <view>
      <selectdept
        ref="Deptref"
        v-model="formData.dep_id"
        @close="select"
        multiple
      >
      </selectdept>
    </view>
  </uv-popup>
</template>

<script setup lang="ts">
import { assign, head, isArray, last, orderBy } from "lodash-es";
import { computed, nextTick, reactive, ref, watch } from "vue";
import selectdept from "@/components/dept/selectdept.vue";
import { useI18n } from "vue-i18n";
import dayjs from "dayjs";
import api from "@/api";
import { onLoad, onShow } from "@dcloudio/uni-app";

import Yellow from "./aichart.vue";
import { navigateTo } from "@/util/navigator";
import { findLeafByLabel } from "@/util";

const $t = useI18n().t;

const pageshow = ref(false);
const list = ref<Eps.aiidentifylabelEntity[]>([]);
const _list = ref<Eps.aiidentifylabelEntity[]>([]);
const formData = reactive({
  dep_id: [],
  feedbackTime: [
    dayjs().subtract(1, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ],
  identifycommentlabels: [],
});

const Deptref = ref();

const poiId = computed(() => {
  if (formData.dep_id.length === 1) {
    return Deptref.value?.list.find(
      (c: Eps.DeptEntity) => c.id === formData.dep_id[0]
    )?.name;
  } else if (formData.dep_id.length === 0) {
    return "所有组织";
  } else {
    return `已筛选：${formData.dep_id.length}个组织`;
  }
});
const popup1 = ref();

function popup1open() {
  popup1.value.open();
}
interface Idata {
  dept_id: string;
  name: string;
  count: string;
  aiidentifylabelid: string;
  release: string;
  Ocount: string;
  id: string;
}
const shopdata = ref<Idata[]>([]);
const red_selected = ref<string>();
const red_selectedshow1 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == red_selected.value && c.type === 1
  )?.length;
});
const red_selectedshow0 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == red_selected.value && c.type === 0
  )?.length;
});
const yellow_selected = ref<string>();
const yellow_selectedshow1 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == red_selected.value && c.type === 1
  )?.length;
});
const yellow_selectedshow0 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == red_selected.value && c.type === 0
  )?.length;
});

const blue_selected = ref<string>();
const blue_selectedshow1 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == blue_selected.value && c.type === 1
  )?.length;
});
const blue_selectedshow0 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == blue_selected.value && c.type === 0
  )?.length;
});
const green_selected = ref<string>();
const green_selectedshow1 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == green_selected.value && c.type === 1
  )?.length;
});
const green_selectedshow0 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == green_selected.value && c.type === 0
  )?.length;
});
const product_selected = ref<string>();
const product_selectedshow1 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == product_selected.value 
  )?.length;
});
const product_selectedshow0 = computed(() => {
  return _list.value.filter(
    (c) => c.parentId == product_selected.value && c.type === 0
  )?.length;
});
const dateacitve = ref<string>("m");

const productcount = ref<Idata[]>([]);

const productshopdata = ref<Idata[]>([]);

const identifycommentlabelcount = ref<any[]>([]);

const show = ref(false);
async function select() {
  popup1.value?.close();
  show.value = false;
  list.value = [];
  // 获取原始数据
  const list1: Eps.aiidentifylabelEntity[] = JSON.parse(
    JSON.stringify(_list.value)
  );
  shopdata.value = [];
  const [n, _shopdata, p, f, _f, fp, _fp] = await Promise.all([
    api<any[]>("/wechat/aiidentifylabel/identifycommentlabelcount", {
      dep_id: formData.dep_id,
      feedbackTime: feedbackTime.value,
    }),
    api<any[]>("/wechat/aiidentifylabel/getshoplabel", {
      dep_id: formData.dep_id,
      feedbackTime: feedbackTime.value,
    }),
    api<any[]>("/wechat/product/identifycommentlabelcount", {
      dep_id: formData.dep_id,
      feedbackTime: feedbackTime.value,
    }),
    api<any[]>("/wechat/aiidentifylabel/identifycommentlabelcount", {
      dep_id: formData.dep_id,
      feedbackTime: _feedbackTime.value,
    }),
    api<any[]>("/wechat/aiidentifylabel/getshoplabel", {
      dep_id: formData.dep_id,
      feedbackTime: _feedbackTime.value,
    }),
    api<any[]>("/wechat/product/identifycommentlabelcount", {
      dep_id: formData.dep_id,
      feedbackTime: _feedbackTime.value,
    }),
    api<any[]>("/wechat/product/getshoplabel", {
      dep_id: formData.dep_id,
      feedbackTime: _feedbackTime.value,
    }),
  ]);
  // 获取当前周期数据
  // const n = await api<any[]>(
  //   "/wechat/aiidentifylabel/identifycommentlabelcount",
  //   { dep_id: formData.dep_id, feedbackTime: feedbackTime.value }
  // );
  identifycommentlabelcount.value = [];
  n.forEach((c) => {
    list1.find((z) => String(z.id) === c.aiidentifylabelid)!.Ncount = c.count;
    identifycommentlabelcount.value.push(assign(c, { release: "N" }));
  });
  // let _shopdata = await api<any[]>("/wechat/aiidentifylabel/getshoplabel", {
  //   dep_id: formData.dep_id,
  //   feedbackTime: feedbackTime.value,
  // });
  shopdata.value = _shopdata.map((c: Idata) => {
    return assign(c, { release: "当前周期", Ocount: 0 });
  });

  // const p = await api<any[]>("/wechat/product/identifycommentlabelcount", {
  //   dep_id: formData.dep_id,
  //   feedbackTime: feedbackTime.value,
  // });

  productcount.value = [];
  p.forEach((c: Idata) => {
    list1.push({
      id: `${c.id}-${c.aiidentifylabelid}`,
      name: c.id,
      parentId: c.aiidentifylabelid,
      Ncount: c.count,
    });
    productcount.value.push(
      assign(c, { release: "N", id: `${c.id}-${c.aiidentifylabelid}` })
    );
  });

  let _productshopdata = await api<any[]>("/wechat/product/getshoplabel", {
    dep_id: formData.dep_id,
    feedbackTime: feedbackTime.value,
  });
  productshopdata.value = _productshopdata.map((c: Idata) => {
    return assign(c, { release: "当前周期", Ocount: 0 });
  });

  // 获取上期周期数据
  // const f = await api<any[]>(
  //   "/wechat/aiidentifylabel/identifycommentlabelcount",
  //   { dep_id: formData.dep_id, feedbackTime: _feedbackTime.value }
  // );
  f.forEach((c) => {
    list1.find((z) => String(z.id) === c.aiidentifylabelid)!.Ocount = c.count;
    identifycommentlabelcount.value.push(assign(c, { release: "O" }));
  });
  // const _f = await api<any[]>("/wechat/aiidentifylabel/getshoplabel", {
  //   dep_id: formData.dep_id,
  //   feedbackTime: _feedbackTime.value,
  // });
  _f.forEach((c) => {
    const n = shopdata.value.find(
      (z) =>
        String(z.aiidentifylabelid) === c.aiidentifylabelid &&
        z.dept_id === c.dept_id
    );
    if (n) {
      n.Ocount = c.count;
    } else {
      shopdata.value.push(
        assign(c, { release: "上期周期", Ocount: c.count, count: 0 })
      );
    }
  });

  // const fp: Idata[] = await api<any[]>(
  //   "/wechat/product/identifycommentlabelcount",
  //   { dep_id: formData.dep_id, feedbackTime: _feedbackTime.value }
  // );
  fp.forEach((c) => {
    const n = list1.find(
      (z) => String(z.id) === `${c.id}-${c.aiidentifylabelid}`
    );
    if (n) {
      n.Ocount = c.count;
    } else {
      list1.push({
        id: `${c.id}-${c.aiidentifylabelid}`,
        name: c.id,
        parentId: c.aiidentifylabelid,
        Ocount: c.count,
      });
    }
    productcount.value.push(
      assign(c, { release: "O", id: `${c.id}-${c.aiidentifylabelid}` })
    );
  });
  // const _fp = await api<any[]>("/wechat/product/getshoplabel", {
  //   dep_id: formData.dep_id,
  //   feedbackTime: _feedbackTime.value,
  // });

  _fp.forEach((c) => {
    const n = productshopdata.value.find(
      (z) =>
        String(z.aiidentifylabelid) === `${c.id}-${c.aiidentifylabelid}` &&
        z.dept_id === c.dept_id
    );
    if (n) {
      n.Ocount = c.count;
    } else {
      productshopdata.value.push(
        assign(c, {
          release: "上期周期",
          Ocount: c.count,
          count: 0,
          id: `${c.id}-${c.aiidentifylabelid}`,
        })
      );
    }
  });
  list.value = list1;
  deepTree(list1);
  show.value = true;
}

onLoad(() => {
  api<Eps.aiidentifylabelEntity[]>("/wechat/aiidentifylabel/list")
    .then((res) => {
      // 渲染数据
      red_selected.value = res.find(
        (c) => c.name === "服务" && !c.parentId
      )?.id;
      blue_selected.value = res.find(
        (c) => c.name === "环境" && !c.parentId
      )?.id;
      green_selected.value = res.find(
        (c) => c.name === "安全" && !c.parentId
      )?.id;
      yellow_selected.value = res.find(
        (c) => c.name === "性价比" && !c.parentId
      )?.id;
      product_selected.value = res.find(
        (c) => c.name === "产品" && !c.parentId
      )?.id;
      console.log(product_selected.value);
      _list.value = res;
      // 渲染数据
      select();
    })
    .catch((f) => {
      console.log(f);
      uni.showToast({
        icon: "error",
        title: f,
        duration: 2000,
      });
    });
});

const feedbackTime = computed(() => {
  let feedbackTime = [
    dayjs().subtract(1, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ];
  if (dateacitve.value === "d") {
    // 天
    feedbackTime = [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")];
  } else if (dateacitve.value === "w") {
    // 7天
    feedbackTime = [
      dayjs().subtract(1, "week").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  } else if (dateacitve.value === "month") {
    //本月
    feedbackTime = [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  } else {
    // 30天
    feedbackTime = [
      dayjs().subtract(30, "day").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ];
  }
  return feedbackTime;
});

const _feedbackTime = computed(() => {
  let feedbackTime = [
    dayjs().subtract(2, "day").format("YYYY-MM-DD"),
    dayjs().format("YYYY-MM-DD"),
  ];
  if (dateacitve.value === "d") {
    feedbackTime = [
      dayjs().subtract(1, "day").format("YYYY-MM-DD"),
      dayjs().subtract(1, "day").format("YYYY-MM-DD"),
    ];
  } else if (dateacitve.value === "w") {
    feedbackTime = [
      dayjs().subtract(2, "week").format("YYYY-MM-DD"),
      dayjs().subtract(1, "week").subtract(1, "day").format("YYYY-MM-DD"),
    ];
  } else if (dateacitve.value === "month") {
    feedbackTime = [
      dayjs()
        .subtract(1, "month")
        .startOf("month")
        .format("YYYY-MM-DD HH:mm:ss"),
      dayjs().subtract(1, "month").startOf("day").format("YYYY-MM-DD HH:mm:ss"),
    ];
  } else {
    feedbackTime = [
      dayjs().subtract(60, "day").format("YYYY-MM-DD"),
      dayjs().subtract(31, "day").format("YYYY-MM-DD"),
    ];
  }
  return feedbackTime;
});

function click(e: any, y: string) {
  const { name } = e;
  const aiidentifylabelid = findLeafByLabel(
    list.value.find((z) => String(z.id) == y)!.children,
    name
  )?.id;
  const _shopdata = shopdata.value.filter(
    (z) => z.aiidentifylabelid == aiidentifylabelid
  );
  uni.setStorageSync("shopdata", JSON.stringify(_shopdata));
  navigateTo(
    `/pages/publicsentiment/shopdata?aiidentifylabelid=${aiidentifylabelid}&type=ai&starttime=${
      feedbackTime.value[0]
    }&endtime=${dayjs(feedbackTime.value[1]).format("YYYY-MM-DD")}`
  );
}

function click1(e: any, y: string) {
  const { name } = e;
  const aiidentifylabelid = findLeafByLabel(
    list.value.find((z) => String(z.id) == y)!.children,
    name
  )?.id;
  const _shopdata = productshopdata.value.filter(
    (z) => `${z.id}-${z.aiidentifylabelid}` == aiidentifylabelid
  );
  uni.setStorageSync("shopdata", JSON.stringify(_shopdata));
  navigateTo(
    `/pages/publicsentiment/shopdata?productid=${aiidentifylabelid}&type=ai&starttime=${
      _feedbackTime.value[0]
    }&endtime=${dayjs(feedbackTime.value[1]).format("YYYY-MM-DD")}`
  );
}

watch(
  () => dateacitve.value,
  () => {
    console.log("dateacitve.value");
    select();
  }
);

function deepTree(list: any[], order?: "asc" | "desc"): any[] {
  const newList: any[] = [];
  const map: any = {};
  list.forEach((e) => (map[e.id] = e));

  list.forEach((e) => {
    const parent = map[e.parentId];

    if (parent) {
      (parent.children || (parent.children = [])).push(e);
    } else {
      newList.push(e);
    }
  });

  const fn = (list: Array<any>) => {
    list.map((e) => {
      if (isArray(e.children)) {
        e.children = orderBy(e.children, "orderNum", order);
        fn(e.children);
      }
    });
  };

  fn(newList);

  return orderBy(newList, "orderNum", order);
}

wx.showShareMenu({
  withShareTicket: true,
});
</script>

<style lang="scss" scoped>
.content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100vw;
}
</style>

<style lang="scss">
#publicsentiment {
  .main {
    margin-top: -36px;
    display: flex;
    flex: 1;
    padding-top: 72rpx;
    padding-left: 32rpx;
    padding-right: 32rpx;
    flex-direction: column;
    background-color: #fff;
    overflow: hidden;
    border-top-left-radius: 48rpx;
    border-top-right-radius: 48rpx;

    .content_form {
      width: calc(100vw - 48rpx);
      padding-left: 24rpx;
      padding-right: 24rpx;
      overflow: hidden;
      background-color: $uni-text-color-inverse;
    }

    .view_input {
      display: flex;
      flex-wrap: wrap;
      flex-shrink: 0;
      flex-grow: 0;
      flex-basis: auto;
      align-items: stretch;
      align-content: flex-start;

      .view_input_left {
        flex: 1;
        overflow: hidden;
        padding-right: 12rpx;
        height: 20px;
        font-size: 15px;
      }

      .view_input_right {
        width: 40rpx;
      }
    }

    .main-header {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      font-weight: 600;
      margin-bottom: 24rpx;
    }

    .main-pingfen {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 24rpx;
      justify-content: space-between;
      gap: 12rpx;

      .identifylabelids-button {
        display: flex;
        flex-wrap: wrap;
        gap: 12rpx;

        .identifylabelids-button-item {
          flex: none;
        }
      }
    }

    .main-pingfen-top {
      display: flex;
      flex-wrap: wrap;
      height: 64rpx;
      align-items: center;
      overflow: hidden;
      text-overflow: ellipsis; //溢出用省略号显示
      white-space: nowrap; //溢出不换行
      font-size: 28rpx;
      width: 400rpx;
    }

    .main-pingfen-top-1 {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
    }

    .main-pingfen-top-2 {
      display: flex;
      flex-wrap: wrap;
      gap: 12rpx;
      margin-left: 40rpx;
    }

    .main-pingfen-date {
      display: flex;
      flex-wrap: wrap;
      border-radius: 24rpx;
      background: linear-gradient(to bottom, #eeeeee, #d8d8d8);
      border: 1rpx solid rgba(200, 200, 200, 1);
      overflow: hidden;

      view {
        width: 64rpx;
        height: 64rpx;
        font-size: 24rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .active {
        color: #fff;
        background-color: #fd754c;
      }

      .border {
        border-left: 1rpx solid rgba(200, 200, 200, 1);
        border-right: 1rpx solid rgba(200, 200, 200, 1);
      }
    }

    .container {
      width: calc(100vw - 64rpx);
      height: 620rpx;

      view {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>
